//
//  ReadViewController.swift
//  Spookiness
//
//  Created by 腾億 on 2017/12/21.
//  Copyright © 2017年 tml. All rights reserved.
//

import UIKit
import NotificationBannerSwift
class ReadViewController: UIViewController {

    fileprivate var edgeInsets: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            return view.safeAreaInsets
        } else {
            return .zero
        }
    }
    
    fileprivate var isLandscapeRight: Bool! {
        didSet {
            UIApplication.changeOrientationTo(landscapeRight: isLandscapeRight)
            collectionView.reloadData()
        }
    }
    
    fileprivate var isBarHidden: Bool = false {
        didSet{
            UIView.animate(withDuration: 0.25) {
                self.topBar.snp.updateConstraints({ (make) in
                    make.top.equalToSuperview().offset(self.isBarHidden ? -(self.edgeInsets.top + kSCREEN_NAVBAR + kSCREEN_STAUSBAR) : 0)
                })
                self.bottomBar.snp.updateConstraints({ (make) in
                    make.bottom.equalTo(self.backScrollView).offset(self.isBarHidden ? (self.edgeInsets.bottom + 120) : 0)
                })
                self.view.layoutIfNeeded()
            }
        }
    }
    
    private var chapterList = [ChapterModel]()
    
    private var detailStatic: DetailStaticModel?
    
    private var selectIndex: Int = 0
    
    private var previousIndex: Int = 0
    
    private var nextIndex: Int = 0
    
    fileprivate lazy var collectionView: UICollectionView = {
       let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .zero
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = kRGBA(r: 242, g: 242, b: 242, a: 1)
        collectionView.register(ReadCell.self, forCellWithReuseIdentifier: "ReadCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.refrshHead = RefreshHeader {
            let previousIndex = self.previousIndex
            self.loadData(with: previousIndex, isPreious: true, needClear: false, finished: {[weak self] (finish) in
                self?.previousIndex = previousIndex - 1
            })
        }
        collectionView.refreshFoot = RefreshAutoFooter {
            let nextIndex = self.nextIndex
            self.loadData(with: nextIndex, isPreious: false, needClear: false, finished: {[weak self] (finish) in
                self?.nextIndex = nextIndex + 1
            })
        }
        return collectionView
    }()
    
    fileprivate lazy var topBar: ReadTopBar = {
       let bar = ReadTopBar()
        bar.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        bar.backButton.addTarget(self, action: #selector(pressBack), for: .touchUpInside)
        return bar
    }()
    
    fileprivate lazy var bottomBar: ReadBottomBar = {
       let bar = ReadBottomBar()
        bar.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        bar.deviceDirectionButton.addTarget(self, action: #selector(changeDeviceDirection(_:)), for: .touchUpInside)
        bar.chapterButton.addTarget(self, action: #selector(changeChapter(_:)), for: .touchUpInside)
        return bar
    }()
    
    fileprivate lazy var backScrollView: UIScrollView = {
       let scroller = UIScrollView()
        scroller.delegate = self
        scroller.addTapGesture(tapNumber: 2, action: {[weak self] (twoTap) in
            var zoomScale = self?.backScrollView.zoomScale
            zoomScale = 2.5 - zoomScale!
            let width = (self?.view.frame.width)! / zoomScale!
            let height = (self?.view.frame.height)! / zoomScale!
            let zoomRect = CGRect(x: (self?.backScrollView.center.x)! - width / 2 , y: (self?.backScrollView.center.y)! - height / 2, width: width, height: height)
            self?.backScrollView.zoom(to: zoomRect, animated: true)
        })
        scroller.addTapGesture(action: {[weak self] (oneTap) in
            self?.isBarHidden = !(self?.isBarHidden)!
        })
        return scroller
    }()
    
    convenience init(detailStatic: DetailStaticModel?, selectIndex: Int) {
        self.init()
        self.detailStatic = detailStatic
        self.selectIndex = selectIndex
        self.previousIndex = selectIndex - 1
        self.nextIndex = selectIndex + 1
    }
    
    fileprivate func loadData(with index: Int, isPreious: Bool, needClear: Bool, finished: ((_ finished: Bool) -> Void)? = nil) {
        guard let detailStatic = detailStatic else {
            return
        }
        self.topBar.titleLabel.text = detailStatic.comic?.name
        if index <= -1 {
            self.collectionView.refreshFoot.endRefreshing()
            warnBar(with: "亲,这已经是第一页了")
        }else if index >= detailStatic.chapter_list.count ?? 0 {
            self.collectionView.refreshFoot.endRefreshingWithNoMoreData()
            warnBar(with: "亲,已经木有了")
        }else {
            guard let chapterId: Int = detailStatic.chapter_list[index].chapter_id else {
                return
            }
            
            NetworkTool.loadChapterData(chapter_id: chapterId) {[weak self] (chapterModel) in
                self?.collectionView.refreshFoot.endRefreshing()
                self?.collectionView.refrshHead.endRefreshing()
                if needClear {
                    self?.chapterList.removeAll()
                }else {
                    self?.chapterList.append(chapterModel)
                }
                self?.collectionView.reloadData()
                guard let finished = finished else { return }
                finished(true)
            }
        }
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        edgesForExtendedLayout = .all
        self.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        self.view.addSubview(self.backScrollView)
        self.backScrollView.addSubview(self.collectionView)
        self.view.addSubview(self.topBar)
        self.view.addSubview(self.bottomBar)
        setUpSnap()
        loadData(with: selectIndex, isPreious: false, needClear: false)
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //状态栏颜色
        UIApplication.shared.statusBarStyle = .default
        self.navigationController?.navigationBar.isHidden = true
        isLandscapeRight = false
    }
    
    fileprivate func setUpSnap() {
        self.backScrollView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view.usnp.edges)
        }
        
        self.topBar.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(kSCREEN_NAVBAR + kSCREEN_STAUSBAR)
        }
        
        self.bottomBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(backScrollView)
            make.height.equalTo(120)
        }
        
        self.collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.height.equalTo(backScrollView)
        }
    }
    
    
    @objc fileprivate func pressBack() {
        isLandscapeRight = false
        if !isLandscapeRight {
            self.navigationController?.popViewController(animated: true)
        }else {
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    @objc fileprivate func changeDeviceDirection(_ button: UIButton) {
        isLandscapeRight = !isLandscapeRight
        if isLandscapeRight {
            button.setImage(#imageLiteral(resourceName: "readerMenu_changeScreen_vertical"), for: .normal)
        }else {
            button.setImage(#imageLiteral(resourceName: "readerMenu_changeScreen_horizontal"), for: .normal)
        }
    }
    
    @objc fileprivate func changeChapter(_ button: UIButton) {
        
    }

    override var prefersStatusBarHidden: Bool {
        return UIScreen.main.bounds.height == 812 ? false : true
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
    fileprivate func warnBar(with string: String) {
        let attributedTitle = NSMutableAttributedString(string: string)
        attributedTitle.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 20), range: (string as NSString).range(of: string))
        let banner = NotificationBanner(attributedTitle: attributedTitle)
        banner.backgroundColor = UIColor.orange
        banner.show()
    }
}

extension ReadViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return chapterList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return chapterList[section].image_list.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        guard let image: ImageListModel = chapterList[indexPath.section].image_list[indexPath.row] else {
            return CGSize.zero
        }
        let height = floor(self.backScrollView.width / CGFloat(image.width) * CGFloat(image.height))
        return CGSize(width: self.backScrollView.width, height: height)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReadCell", for: indexPath) as! ReadCell
        cell.model = chapterList[indexPath.section].image_list[indexPath.row]
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isBarHidden == false { isBarHidden = true }
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        if scrollView == backScrollView {
            return collectionView
        } else {
            return nil
        }
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        if scrollView == backScrollView {
            scrollView.contentSize = CGSize(width: scrollView.frame.width * scrollView.zoomScale, height: scrollView.frame.height)
        }
    }
    
}



